//
//  WBStatusPictureView.swift
//  Weibo
//
//  Created by yinbo on 2018/3/22.
//  Copyright © 2018年 yinbo. All rights reserved.
//

import UIKit

class WBStatusPictureView: UIView {
    
    var viewModel:WBStatusViewModel?{
        didSet{
            calcViewSize()
            urls = viewModel?.picURLs
        }
    }
    //根据视图模型的配图视图大小，调整显示内容
    func calcViewSize(){
        //单图，根据配图是的大小，修改subview[0]的宽高
        
        if viewModel?.picURLs?.count == 1{
            let viewSize = viewModel?.pictureViewSize ?? CGSize()
            let v = subviews[0]
            v.frame =  CGRect(x: 0, y: WBStatusPictureViewOutterMargin, width: viewSize.width, height: viewSize.height-WBStatusPictureViewOutterMargin)
        }else{
            let v = subviews[0]
            v.frame =  CGRect(x: 0, y: WBStatusPictureViewOutterMargin, width:WBStatusPictureItemWidth, height: WBStatusPictureItemWidth)
        }
        
        //多图，恢复subview[0]的宽高，保证九宫格布局的完整
        heightCons.constant = viewModel?.pictureViewSize.height ?? 0
    }
    private var urls:[WBStatusPicture]?{
        didSet{
            //1.隐藏所有的IMAGEVIEW
            for v in subviews{
                v.isHidden = true
            }
            var index = 0
            for  url in urls ?? []{
                //获得对应索引的imageView
                let iv = subviews[index] as! UIImageView
                if index==1&&urls?.count==4{
                    index+=1
                }
                 iv.cz_setImage(urlString: url.thumbnail_pic, placeholderImage: nil)
                iv.isHidden=false
                index+=1

                
            }
        }
    }
    @IBOutlet weak var heightCons:NSLayoutConstraint!
    override func awakeFromNib() {
        setupUI()
    }
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
extension WBStatusPictureView{
    //1.Cell中所有的空间都是提前准备好
    //2.设置的时候，根据数据决定是否显示
    //3.不要动态创建控件
    
    func setupUI(){
        let count = 3
        backgroundColor = superview?.backgroundColor
        //超出边界的不显示
        clipsToBounds = true
        let rect = CGRect(x: 0,y: WBStatusPictureViewOutterMargin, width: WBStatusPictureItemWidth, height: WBStatusPictureItemWidth)
        for i in 0..<count*count{
            let iv = UIImageView()
            let row = CGFloat(i/count)
            let col = CGFloat(i%count)
            let xOffset = col*(WBStatusPictureItemWidth+WBStatusPictureViewInnerMargin)
            let yOffset = row*(WBStatusPictureItemWidth+WBStatusPictureViewInnerMargin)
            iv.frame = rect.offsetBy(dx: xOffset, dy: yOffset)
            self.addSubview(iv)
        }
    }
}
